import { useContext } from "react";
import "./index.css";
import { PageContext } from "../../store/index";
import { componentsList } from "../../components";
import { cloneDeep } from "lodash";

export const Config = () => {
  const { currentConfigId, list, setList } = useContext(PageContext);

  const renderConfig = () => {
    if (currentConfigId) {
      // list 中找到 id 为 currentConfigId 的组件
      const currentComponent = list.find((item) => item.id === currentConfigId);
      const currentComponentName = currentComponent.name;

      const allProps = componentsList.find(
        (item) => item.name === currentComponentName
      ).propsType;

      const currentProp = currentComponent.props;

      const handleChange = (e, name) => {
        const value = e.target.value;
        const copiedList = cloneDeep(list);
        const target = copiedList.find((item) => item.id === currentConfigId);
        target.props[name] = value;
        setList(copiedList)
      };

      return (
        <div>
          <div>当前组件：{currentComponentName}</div>
          <div>
            {allProps.map((item) => {
              return (
                <div>
                  <div>{item.name}</div>:
                  <input
                    value={currentProp[item.name]}
                    onChange={(e) => handleChange(e, item.name)}
                  />
                </div>
              );
            })}
          </div>
        </div>
      );
    } else {
      return <div>请先选择你要配置的组件</div>;
    }
  };

  return (
    <div className="config-container">
      <div>配置区</div>
      <div>{renderConfig()}</div>
    </div>
  );
};
